package com.google.code.drift.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.code.drift.R;
import com.google.code.drift.animation.Rotate3dAnimation;
import com.google.code.drift.api.Refreshable;
import com.google.code.drift.dialog.AboutDialog;
import com.google.code.drift.dialog.ChooseCityDialog;
import com.google.code.drift.service.DriftService;
import com.google.code.drift.service.DriftService.DriftServiceBinder;
import com.google.code.drift.utils.CommonUtils;
import com.google.code.drift.utils.DLog;
import com.google.code.drift.utils.JsonFactory;
import com.google.code.drift.utils.PreferencesProxy;

public class MainActivity extends AbstractActivityGroup implements
		OnClickListener {

	private static final int QUIT_DIALOG = 0;

	private static final int RELOGIN_DIALOG = 1;

	private LinearLayout container;
	private TextView listTabButton;
	private TextView mapChatButton;
	private TextView userTabButton;

	private RelativeLayout editLayout;
	private EditText editText;
	private Button sendButton;

	private ImageView modSwitcher;
	private ImageView refreshButton;

	private boolean serviceIsRegistered = false;

	// 默认刚启动时是地图模式
	private boolean isMapMod = true;

	private DriftService myService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		DLog.i("MainActivity onCreate");
		PreferencesProxy.init(this, false);
		initView();
	}

	@Override
	protected void onStart() {
		super.onStart();
		DLog.i("MainActivity onStart");
		initMainHandler();
		if (!app.isLogin()) {
			bindMyService();
		} else {
			DLog.i("[MainActivity:] 已经登录过了！");
		}
	}

	@Override
	protected void onDestroy() {
		// 第一时间把在线状态设置false
		// 否则后果很严重....
		app.setLoginState(false);
		unbindMyService();
		stopService(new Intent(MainActivity.this, DriftService.class));
		super.onDestroy();
	}

	@Override
	protected void initActionBar() {
		initBar();
		setupBar();
	}

	private static final int GOING_TO = 2;

	private static final int ABOUT = 3;

	private static final int QUIT = 4;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuItem goingTo = menu.add(0, GOING_TO, 0, R.string.going_to);
		goingTo.setIcon(R.drawable.ic_going_to);

		MenuItem about = menu.add(0, ABOUT, 0, R.string.about);
		about.setIcon(R.drawable.ic_about);

		MenuItem quit = menu.add(0, QUIT, 0, R.string.exit);
		quit.setIcon(R.drawable.ic_quit);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case GOING_TO:
			new ChooseCityDialog(this).show();
			break;
		case ABOUT:
			new AboutDialog(MainActivity.this).show();
			break;
		case QUIT:
			showDialog(QUIT_DIALOG);
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog(QUIT_DIALOG);
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case QUIT_DIALOG:
			return new AlertDialog.Builder(MainActivity.this)
					.setIcon(R.drawable.ic_interrogative)
					.setTitle(R.string.sure_quit_app)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									unbindMyService();
									finish();
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		case RELOGIN_DIALOG:
			return new AlertDialog.Builder(MainActivity.this)
					.setIcon(R.drawable.ic_interrogative)
					.setTitle(R.string.sure_relogin)
					.setCancelable(false)
					.setPositiveButton(R.string.retry,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									myService.reLogin();
								}
							})
					.setNegativeButton(R.string.exit,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									unbindMyService();
									finish();
								}
							}).show();
		default:
			return super.onCreateDialog(QUIT_DIALOG);
		}
	}

	private Intent tabIntent;

	@Override
	public void onClick(View v) {
		setIntentAndButtonState(v.getId());
	}

	private void initBar() {
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.action_bar);
		modSwitcher = (ImageView) findViewById(R.id.action_bar_chat_mod_switcher);
		refreshButton = (ImageView) findViewById(R.id.action_bar_refresh_button);
	}

	private void setupBar() {
		modSwitcher.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switchChatMod();
			}
		});
		refreshButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				RotateAnimation rotation = new RotateAnimation(1, 3 * 180,
						Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);
				rotation.setDuration(1000);
				// refreshButton.getDrawable().setAlpha(60);
				refreshButton.startAnimation(rotation);
				refreshView();
			}
		});
	}

	private void initView() {

		container = (LinearLayout) findViewById(R.id.main_activity_container);
		listTabButton = (TextView) findViewById(R.id.main_list_tab);
		mapChatButton = (TextView) findViewById(R.id.main_map_tab);
		userTabButton = (TextView) findViewById(R.id.main_user_tab);
		editLayout = (RelativeLayout) findViewById(R.id.edit_layout);
		editText = (EditText) findViewById(R.id.edit_text);
		sendButton = (Button) findViewById(R.id.send_button);

		listTabButton.setOnClickListener(this);
		mapChatButton.setOnClickListener(this);
		userTabButton.setOnClickListener(this);
		sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = editText.getText().toString();
				if (CommonUtils.isNotNullString(content.trim())) {
					editText.setText(null);
					sendToServerAndSendToMe(content);
				} else {
					showToast(R.string.content_not_null, Toast.LENGTH_SHORT);
				}
			}
		});

	}

	/**
	 * 给自己发的目的是，刷新自己的聊天View
	 * 
	 * @param content
	 */
	private void sendToServerAndSendToMe(String content) {
		JSONObject json = makeAndSendSayJson(content);
		json = json.getJSONObject("data");
		// 这里是给自己发的广播，所以只要data字段
		// 这个data字段里的内容就是刚刚生成的那个
		CommonUtils.receiveChatDataFromServer(this, json.toJSONString());
	}

	private JsonFactory jsonFactory = JsonFactory.getFactory();

	private JSONObject makeAndSendSayJson(String content) {
		JSONObject json = jsonFactory.makeSayContentJson(app.getMyInfo()
				.getUserId(), content, app.getMyInfo().getNick(), app
				.getMyInfo().getSex());
		CommonUtils.sendDataToServer(this, json.toJSONString());
		return json;
	}

	private void setIntentAndButtonState(int id) {

		setAllButtonToDefault();

		switch (id) {
		case R.id.main_list_tab:
			tabIntent = new Intent(this, ListTabActivity.class);
			setButtonAndEditAndModState(listTabButton,
					R.drawable.ic_tab_tradition_selected);
			editLayout.setVisibility(View.GONE);
			modSwitcher.setVisibility(View.GONE);
			refreshButton.setVisibility(View.VISIBLE);
			break;
		case R.id.main_map_tab:
			setButtonAndEditAndModState(mapChatButton,
					R.drawable.main_tab_map_selected);
			editLayout.setVisibility(View.VISIBLE);
			modSwitcher.setVisibility(View.VISIBLE);
			refreshButton.setVisibility(View.VISIBLE);
			if (isMapMod) {
				tabIntent = new Intent(this, MapChatActivity.class);
				id = R.layout.chat_map_mod_layout;
			} else {
				tabIntent = new Intent(this, TraditionChatActivity.class);
				id = R.layout.chat_tradition_mod_layout;
			}
			break;
		case R.id.main_user_tab:
			tabIntent = new Intent(this, ProfileTabActivity.class);
			setButtonAndEditAndModState(userTabButton,
					R.drawable.main_tab_profile_selected);
			editLayout.setVisibility(View.GONE);
			modSwitcher.setVisibility(View.GONE);
			refreshButton.setVisibility(View.GONE);
			break;
		default:
			// TODO 这什么情况！！不可能调用啊！
			DLog.i("添加Flags");
			tabIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			break;
		}

		setActivity(id);
	}

	private void setButtonAndEditAndModState(TextView button, int selectedIc) {
		setTabButtonState(button, selectedIc,
				R.drawable.main_tab_selected_background, Color.WHITE);
	}

	private void setAllButtonToDefault() {
		setTabButtonState(listTabButton, R.drawable.ic_tab_tradition_default,
				R.drawable.main_tab_default_background, getResources()
						.getColor(R.color.text_color_dark));
		setTabButtonState(mapChatButton, R.drawable.main_tab_map_default,
				R.drawable.main_tab_default_background, getResources()
						.getColor(R.color.text_color_dark));
		setTabButtonState(userTabButton, R.drawable.main_tab_profile_default,
				R.drawable.main_tab_default_background, getResources()
						.getColor(R.color.text_color_dark));
	}

	private void setTabButtonState(TextView tabButton, int drawId,
			int backgroundId, int color) {
		tabButton.setCompoundDrawablesWithIntrinsicBounds(0, drawId, 0, 0);
		tabButton.setBackgroundResource(backgroundId);
		tabButton.setTextColor(color);
	}

	private void setActivity(int id) {
		container.removeAllViews();
		View activity = getLocalActivityManager().startActivity(
				String.valueOf(id), tabIntent).getDecorView();
		LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		container.addView(activity, lp);
	}

	private void switchChatMod() {

		View modView = makeViewFromActivity();

		rotateToChatMod(new SwapView(modView));

	}

	private View makeViewFromActivity() {
		Intent intent;
		int id;
		if (isMapMod) {// 当前是地图模式，那么切换到传统模式
			isMapMod = false;
			intent = new Intent(this, TraditionChatActivity.class);
			modSwitcher.setImageResource(R.drawable.switcher_list);
			id = R.layout.chat_tradition_mod_layout;
		} else {// 当前是传统模式，将切换到地图模式
			isMapMod = true;
			intent = new Intent(this, MapChatActivity.class);
			modSwitcher.setImageResource(R.drawable.switcher_map);
			id = R.layout.chat_map_mod_layout;
		}
		View modView = getLocalActivityManager().startActivity(
				String.valueOf(id), intent).getDecorView();
		return modView;
	}

	private void rotateToChatMod(Runnable action) {

		Animation rotation = new Rotate3dAnimation(0, 90,
				(container.getWidth() / 2.0f), (container.getHeight() / 2.0f),
				0);
		rotation.setDuration(250);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new RotateListener(action));
		container.startAnimation(rotation);

	}

	private void initMainHandler() {
		DLog.i("重置 app.progressAndToastHandler");
		app.setUpdateUIHandler(new ShowHandler());
	}

	/**
	 * 这个类实现的太乱了，一定要整理整理
	 * 
	 * @author zkwlx
	 * 
	 */
	private class ShowHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == CommonUtils.START_PROGRESS) {
				showProgress(msg);
			} else if (msg.what == CommonUtils.NOTIFY_ONCE_ACTION) {
				Bundle bundle = msg.getData();
				showToast(bundle.getString("data"));
				refreshView();
				dismissProgress();
			} else {
				// 登录！
				onClick(mapChatButton);
				dismissProgress();
				loginMessageProcess(msg.what);
			}
		}

	}

	private void loginMessageProcess(int what) {
		switch (what) {
		case CommonUtils.REGISTER_SUCCESS:// 如果是注册成功，要在本地储存返回的newId
			showToast("注册成功！");
			refreshView();
			DLog.i("注册成功！！");
			break;
		case CommonUtils.LOGIN_SUCCESS:
			showToast("登录成功！");
			refreshView();
			DLog.i("登录成功！！");
			break;
		case CommonUtils.LOGIN_TIMEOUT:
			showToast("超时，请重试！");
			showDialog(RELOGIN_DIALOG);
			DLog.i("登录超时！");
			break;
		case CommonUtils.LOGIN_ERROR:
			showToast("登录失败，请重试！");
			// XXX 关闭APN时候测试用
			showDialog(RELOGIN_DIALOG);
			DLog.i("登录异常！");
			break;

		}
	}

	/**
	 * 刷新当前Activity
	 */
	private void refreshView() {
		if (app.isAutoRefresh()) {
			String id = getLocalActivityManager().getCurrentId();
			int currentId = Integer.valueOf(id);
			refreshCurrentView(currentId);
		}
	}

	private void refreshCurrentView(int currentId) {
		Refreshable view = (Refreshable) getLocalActivityManager().getActivity(
				String.valueOf(currentId));
		if (view != null)
			view.refresh();
	}

	private void bindMyService() {
		if (!serviceIsRegistered) {
			Intent serviceIntent = new Intent(MainActivity.this,
					DriftService.class);
			bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
			serviceIsRegistered = true;
		}
	}

	private void unbindMyService() {
		if (serviceIsRegistered) {
			unbindService(mServiceConnection);
			serviceIsRegistered = false;
		}
	}

	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			DLog.i("ServiceConnection is Connected");
			myService = ((DriftServiceBinder) service).getService();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// 注意！！
			// 只有出现异常情况导致连接丢失，这个方法才会调用！
			DLog.i("ServiceConnection is Disconnected");
			myService = null;
		}
	};

	private final class RotateListener implements AnimationListener {

		Runnable action;

		public RotateListener(Runnable action) {
			this.action = action;
		}

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			container.post(action);
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

	}

	private class SwapView implements Runnable {

		View modView;

		public SwapView(View modView) {
			this.modView = modView;
		}

		@Override
		public void run() {
			LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			container.removeAllViews();
			container.addView(modView, lp);
			// 这两个角度是避免View旋转好后是左右相反的
			Animation rotation = new Rotate3dAnimation(270, 360,
					(container.getWidth() / 2.0f),
					(container.getHeight() / 2.0f), 0);
			rotation.setDuration(250);
			rotation.setInterpolator(new DecelerateInterpolator());
			container.startAnimation(rotation);
		}

	}

}
